<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    <el-button
      icon="el-icon-s-check"
      style="margin-left: 20px"
      type="primary"
      size="small"
      v-if="draggable"
      @click="saveNode"
      >保存</el-button
    >
    <el-button
      size="small"
      type="primary"
      style="margin-left: 20px"
      icon="el-icon-document-add"
      @click="addHandler"
      >添加</el-button
    >
    <el-tree
      ref="tree"
      :data="tableData"
      :draggable="draggable"
      :expand-on-click-node="false"
      :default-expanded-keys="expandedKeys"
      :current-node-key="currentNodeKey"
      node-key="value"
      @node-click="handleTreeNodeClick"
      @node-expand="handleNodeExpand"
      @node-collapse="handleNodeCollapse"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span :style="{ color: isExpired(data.endTime) ? 'red' : 'inherit' }">
          {{ data.label }}
        </span>

        <span>
          <el-switch
            @change="changeOnService(data)"
            v-model="data.canService"
            active-text="上架"
            inactive-text="下架"
          />
          <el-switch
            @change="changeNeedTest(data)"
            v-model="data.needTest"
            active-text="需要考试"
            inactive-text="无需考试"
            style="margin-left: 10px"
          />
          <el-button
            v-if="data.children.length == 0 && data.needTest"
            type="text"
            style="color: rgb(139, 220, 112); margin-left: 10px"
            size="mini"
            @click="getScore(data)"
            >查看成绩</el-button
          >
          <el-button
            type="text"
            style="color: goldenrod; margin-left: 10px"
            size="mini"
            @click="handleDetailClick(data)"
            >详情</el-button
          >
          <el-button type="text" size="mini" @click="handleNodeClick(data)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            style="color: rgb(258, 182, 182); margin-left: 10px"
            type="text"
            @click="removeHandler(data)"
            >删除</el-button
          >
        </span>
      </span>
    </el-tree>
    <el-dialog
      @close="handleClose"
      :visible.sync="dialogVisible"
      title="成绩详情"
      width="70%"
    >
      <h4>未考人员</h4>
      <div class="names-grid">
        <div v-for="name in names" :key="name">姓名：{{ name }}</div>
      </div>
      <el-table :data="scoreData" style="width: 100%">
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="score" label="得分" />
        <el-table-column prop="subjectId" label="课程" />
        <el-table-column prop="usedTime" label="用时" />
        <el-table-column prop="endTime" label="完成时间" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import subjectApi from "@/api/subject/index";
import testApi from "@/api/subject/test";
export default {
  data() {
    return {
      tableData: [],
      scoreData: [],
      draggable: false,
      dialogVisible: false,
      names: [],
      expandedKeys: [], // 存储展开的节点
      currentNodeKey: null, // 当前选中的节点
    };
  },
  methods: {
    // 保存树状态
    saveTreeState() {
      localStorage.setItem(
        "education-tree-expanded-keys",
        JSON.stringify(this.expandedKeys)
      );
      localStorage.setItem("education-tree-current-node", this.currentNodeKey);
    },

    // 恢复树状态
    restoreTreeState() {
      try {
        const savedExpandedKeys = localStorage.getItem(
          "education-tree-expanded-keys"
        );
        const savedCurrentNode = localStorage.getItem(
          "education-tree-current-node"
        );

        if (savedExpandedKeys) {
          this.expandedKeys = JSON.parse(savedExpandedKeys);
        }

        if (savedCurrentNode) {
          this.currentNodeKey = savedCurrentNode;
        }
      } catch (e) {
        console.error("恢复树状态时出错:", e);
      }
    },

    // 节点点击时不仅执行原有操作，还记录当前节点
    handleTreeNodeClick(data) {
      this.currentNodeKey = data.value;
      this.saveTreeState();
    },

    // 记录展开的节点
    handleNodeExpand(data) {
      if (!this.expandedKeys.includes(data.value)) {
        this.expandedKeys.push(data.value);
        this.saveTreeState();
      }
    },

    // 移除折叠的节点
    handleNodeCollapse(data) {
      const index = this.expandedKeys.indexOf(data.value);
      if (index !== -1) {
        this.expandedKeys.splice(index, 1);
        this.saveTreeState();
      }
    },

    isExpired(endTime) {
      if (!endTime) return false;
      return new Date(endTime) < new Date();
    },
    changeOnService(data) {
      subjectApi.updateService(data.canService, data.value).then((res) => {
        this.$message({
          message: `${res.data}`,
          type: "success",
        });
        subjectApi.getAllTree().then((res1) => {
          this.tableData = res1.data;
          // 在数据更新后恢复状态
          this.$nextTick(() => {
            this.restoreTreeState();
          });
        });
      });
    },
    changeNeedTest(data) {
      subjectApi.updateNeedTest(data.needTest, data.value).then((res) => {
        this.$message({
          message: `${res.data}`,
          type: "success",
        });
        subjectApi.getAllTree().then((res1) => {
          this.tableData = res1.data;
          // 在数据更新后恢复状态
          this.$nextTick(() => {
            this.restoreTreeState();
          });
        });
      });
    },
    saveNode: async function () {
      subjectApi.updateTree(this.tableData).then((res) => {
        this.$message({
          message: "更新成功！",
          type: "success",
        });
        this.draggable = false;
      });
    },
    removeHandler: async function (data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          subjectApi.delete(data.value).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            subjectApi.getAllTree().then((res1) => {
              this.tableData = res1.data;
              // 在数据更新后恢复状态
              this.$nextTick(() => {
                this.restoreTreeState();
              });
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleClose() {
      this.scoreData = [];
      this.names = [];
    },
    handleNodeClick(data) {
      // 保存状态后再跳转
      this.currentNodeKey = data.value;
      this.saveTreeState();

      const flag = data.children.length == 0 ? 0 : 1;
      this.$router.push({
        path: "/education/edit",
        query: { id: data.value, flag: flag, disabled: 0 },
      });
    },
    handleDetailClick(data) {
      // 保存状态后再跳转
      this.currentNodeKey = data.value;
      this.saveTreeState();

      const flag = data.children.length == 0 ? 0 : 1;
      this.$router.push({
        path: "/education/edit",
        query: { id: data.value, flag: flag, disabled: 1 },
      });
    },
    addHandler() {
      // 保存当前状态再跳转
      this.saveTreeState();

      this.$router.push({
        path: "/education/edit",
        query: { id: -1, disabled: 0 },
      });
    },
    getScore(data) {
      testApi.getBySubjectId(data.value).then((res) => {
        if (res.data) {
          this.scoreData = res.data.subjectTests;
          this.names = res.data.names;
          this.dialogVisible = true;
        } else {
          this.$message({
            message: "暂无成绩",
            type: "warning",
          });
        }
      });
    },
  },
  created() {
    // 先恢复状态
    this.restoreTreeState();

    // 然后获取数据
    subjectApi.getAllTree().then((res1) => {
      this.tableData = res1.data;
      // 在数据加载完成后，确保状态能被正确应用
      this.$nextTick(() => {
        this.restoreTreeState();
      });
    });
  },
  // 在组件销毁前保存状态
  beforeDestroy() {
    this.saveTreeState();
  },
};
</script>

<style scoped>
.iframe-wrapper {
  text-align: center;
}
.iframe-wrapper iframe {
  display: block; /* 关键：将内联元素转为块级 */
  margin: 0 auto; /* 水平居中 */
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.names-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 将容器分为3列，每列宽度相等 */
  gap: 16px; /* 设置元素之间的间距 */
}
</style>
